<?php


namespace app\admin\system\controller;


use app\admin\system\logic\LoginLogic;
use app\admin\system\logic\MenuLogic;
use app\admin\system\validate\AdminLoginValidate;
use app\common\controller\BaseAdminController;
use app\common\service\ConfigService;
use common\service\JwtService;
use core\service\GeeTestService;

class LoginController extends BaseAdminController
{
    /**
     * @var LoginLogic
     */
    private LoginLogic $loginLogic;

    protected function init()
    {
        $this->logic = new MenuLogic();
        $this->loginLogic = new LoginLogic();
        parent::init();
    }

    protected $noNeedLogin = [
        'login',
        'checkGeeTest',
        'getLoginConfig',
    ];
    protected $noNeedRight = [
        '*'
    ];

    public function my()
    {
        $uid = request()->uid;

        $data = $this->logic->myLoginAuth($uid);
        return $this->success($data);
    }

    public function login()
    {
        AdminLoginValidate::goCheck(input());
        $username = base64_decode(input('username'));//base64_decode
        $password = base64_decode(input('password'));
        $ext = [
            'token' => base64_decode(input('token')),
            'code' => base64_decode(input('code')),
            'google_authenticator_code' => base64_decode(input('google_authenticator_code')),
        ];
        $res = $this->loginLogic->login($username, $password, $ext);
        return $this->success($res);
    }

    public function loginOut()
    {
        JwtService::logout('admin');
        return $this->success();
    }

    /**
     * @return false|string
     */
    public function checkGeeTest()
    {
        $config = ConfigService::getConfig('LOGIN_CONFIG');
        $res = GeeTestService::validate($config, input());
        if ($res['result'] === "success") {
            return $this->success();
        } else {
            return $this->error();
        }
    }

    /**
     * @return false|string
     */
    public function getLoginConfig()
    {
        $config = ConfigService::getConfig('LOGIN_CONFIG');
        unset($config['geetest_key']);
        return $this->success($config);
    }

}
